import { createRouter, createWebHashHistory } from 'vue-router';
//获取pinia
import { useUserStore } from '@/store/index';
//自定义路由
import { setItem, getItem } from '@/utils/componen.ts';
// 本地静态路由
const routes: any = [
  {
    path: '/login',
    name: 'login',
    replace: true,
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
    },
  },
  {
    path: '/',
    name: 'layout',
    replace: true,
    component: () => import('@/layout/index.vue'),
    meta: {
      title: '主页',
    },
    children: [],
  },
];
//可使用路由
const routesArr: any = [];
const comps = import.meta.glob('../views/**/index.vue');
const pages = import.meta.glob('../views/**/page.ts', {
  eager: true,
  import: 'default',
});
//获取菜单目录信息
const _objPages = Object.entries(pages);
_objPages.forEach(([path, meta]) => {
  setPath(path, meta);
});
//设置路由信息
function setPath(path: any, meta: any) {
  const notChilch: any = ['404', 'login', 'add', 'details'];
  const compPath = path.replace('page.ts', 'index.vue');
  path = path.replace('../views', '').replace('/page.ts', '') || '/';
  const pathArray = path.split('/').filter(Boolean); // 过滤掉空字符串
  const name = pathArray.join('-') || 'index';
  const objPath = {
    path: path,
    name: name,
    component: comps[compPath],
    meta: meta,
  };
  if (notChilch.includes(name)) {
    routes.push(objPath);
  } else {
    const index = routes.findIndex((el: any) => el.children);
    routes[index].children.push(objPath);
  }
  routesArr.push(path);
}

// 创建路由
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});
// 现在，我们将监听路由变化
router.beforeEach((to, from, next) => {
  const userStores: any = useUserStore();
  userStores.routesArr = routesArr;
  if (to.path === '/login' || getItem('apiToken')) {
    //获取菜单名称
    window.document.title = `${to.meta.title}`;
    if (routesArr.includes(to.path) || to.path === '/') {
      if (!['/404', '/login'].includes(to.path)) {
        userStores.activeMenu = to.path;
        if (!to.path.includes('details')) {
          setItem('toPath', to.path);
        }
      }
      next();
    } else {
      if (userStores.menuTab.length > 1) {
        userStores.menuTab.splice(userStores.menuTab.length - 1, 1);
        setItem('menuTab', userStores.menuTab);
      }
      next('/404');
    }
  } else {
    localStorage.clear();
    next('/login');
  }
});

export default router;
